package com.google.jessewilson.codesearch.intellij;

import com.google.inject.Inject;
import com.google.jessewilson.codesearch.api.Query;
import com.google.jessewilson.codesearch.ide.QueryHistory;

import java.io.File;
import java.util.List;

/**
 * @author jessewilson
*/
class CodeSearchRunner {
  private final SearchTermFinder searchTermFinder;
  private final PreflightQueryEditorDialog preflightQueryEditorDialog;
  private final QueryHistory queryHistory;

  @Inject
  public CodeSearchRunner(
      SearchTermFinder searchTermFinder,
      PreflightQueryEditorDialog preflightQueryEditorDialog,
      QueryHistory queryHistory) {
    this.searchTermFinder = searchTermFinder;
    this.preflightQueryEditorDialog = preflightQueryEditorDialog;
    this.queryHistory = queryHistory;
  }

  public void execute(File editorFile) {
    Query.Builder queryBuilder = new Query.Builder();

    // apply the prototype query
    List<Query> queryHistorySnapshot = this.queryHistory.getSnapshot();
    if (!queryHistorySnapshot.isEmpty()) {
      Query prototype = queryHistorySnapshot.get(0);
      queryBuilder.baseQuery(prototype);
    }

    // apply the editor file
    queryBuilder.editorFile(editorFile);

    // apply the search term
    queryBuilder.searchTerm(searchTermFinder.getBestSearchTerm());

    // show the dialog
    Query query = queryBuilder.build();
    preflightQueryEditorDialog.show(query);
  }
}
